package com.java110.mall.chain.supplier.adaper.llk;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * AES 加密算法 工具类
 */
public class AesUtils {
    private final static Logger logger = LoggerFactory.getLogger(AesUtils.class);

    /**
     * 加密
     *
     * @param data      对象转为json字符串
     * @param secretKey AES秘钥
     * @return 加密后的字符串
     */
    public static String aesEncrypt(String data, String secretKey) {
        try {
            // 加密算法/工作模式/填充方式
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] dataBytes = data.getBytes("UTF-8");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64Utils.decodeFromString(secretKey), "AES"));
            byte[] result = cipher.doFinal(dataBytes);
            return Base64Utils.encodeToString(result);
        } catch (Exception e) {
            logger.debug("执行CodecUtil.aesEncrypt失败：data={}，异常：{}", data, e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param encryptedDataBase64 加密后的字符串
     * @param securityKey         AES秘钥
     * @return 解密后的json字符串
     */
    public static String aesDecrypt(String encryptedDataBase64, String securityKey) {
        try {
            // 加密算法/工作模式/填充方式
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] dataBytes = Base64Utils.decodeFromString(encryptedDataBase64);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64Utils.decodeFromString(securityKey), "AES"));
            byte[] result = cipher.doFinal(dataBytes);
            return new String(result,StandardCharsets.UTF_8);
        } catch (Exception e) {
            logger.debug("执行aesDecrypt失败：data={}，异常：{}", encryptedDataBase64, e);
        }
        return null;
    }

    public static void main(String[] args) {
        String aesEncrypt = AesUtils.aesEncrypt("123", "ri17cWAp0rvozL9Cb94xtQ==");
        String aesDecrypt = AesUtils.aesDecrypt(aesEncrypt, "ri17cWAp0rvozL9Cb94xtQ==");
        System.out.println(aesDecrypt);
    }

}
